package com.syni.mdd.yhd.common.all.controller.protect.alipay;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.utils.RpcResponseVo;
import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckParams;
import com.syni.mdd.yhd.common.all.config.pay.alipay.AlipayConfig;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.controller.pay.wxPay.WxPayController;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.BmsDxOrderService;
import com.syni.mdd.yhd.common.all.service.pay.aiPay.AliPayService;
import com.syni.mdd.yhd.common.all.service.pay.aiPay.AlipayServiceImpl;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.TokenManager;
import com.syni.mdd.yhd.common.all.utils.TokenUtils;
import com.syni.mdd.yhd.common.all.vo.rp.user.AuthMiniAppUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@RestController
@RequestMapping("/aliMinApp")
public class AliMinAppController {

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    @Qualifier("aliMiniAppConfig")
    AlipayConfig aliMiniAppConfig;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    WxPayController wxPayController;

    private final Logger log = LoggerFactory.getLogger(getClass());


    /**
     * 发起支付
     * @param merchantId 个体商户号
     * @param subject 支付标题
     * @param body 支付内容
     * @param totalAmt 支付金额（元）
     * @return
     */
    @CheckParams(params = {"authCode"})
    @PostMapping("/auth")
    @ResponseBody
    public Map<String,Object> auth(@RequestBody ParamsMap paramsMap) {
        String authCode = paramsMap.getString("authCode");
        AlipayClient alipayClient = aliPayService.getAliMiniAppClient();
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
        request.setCode(authCode);
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("aliUserId : " + response.getUserId());
                log.info("accessToken : " + response.getAccessToken());
                return aliPayService.authMiniAppUser(response);
            }
        } catch (AlipayApiException e) {
            log.error(e.getMessage(),e);
        }
        return ResultMapHelper.result(ResultCode.CODE_ERROR_100,ResultMsg.HAND_FAIL);
    }

    @CheckParams(params = {"avatar","nickName","gender","province","userId"})
    @PostMapping("/saveUserMes")
    @ResponseBody
    public Map<String,Object> saveUserMes(@RequestBody ParamsMap paramsMap) {
        return aliPayService.saveUserMes(paramsMap);
    }

    /**
     * 获取小程序手机
     * @param paramStr 加密字符串
     * @return
     */
    @PostMapping("/miniAppPhone")
    @ResponseBody
    public Map<String,Object> getMiniAppPhone(@RequestBody ParamsMap paramsMap) {
        String paramStr = paramsMap.getString("paramStr");
        String aliUserId = paramsMap.getString("aliUserId");
        return aliPayService.miniAppPhone(aliUserId,paramStr);
    }

    /**
     * @Description 支付宝小程序支付
     * @Author: cfx
     * @Date: 2019/8/2
     */
    @CheckParams(params = {"orderId","orderNo"})
    @PostMapping("/prepay")
    @ResponseBody
    public Map<String,Object> prepay(@RequestBody ParamsMap paramsMap) {
        Map<String, Object> resultMap = new HashMap<>();
        Integer orderId = Integer.parseInt(paramsMap.get("orderId").toString());
        String orderNo = paramsMap.get("orderNo").toString();
        //检验订单号和订单id是否一致
        Optional<BmsDxOrder> bmsDxOrderOptional = bmsDxOrderService.getBaseDao().findById(orderId);
        if (!bmsDxOrderOptional.isPresent()) {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_NO_EXIST, ResultMsg.CODE_ORDER_NO_EXIST);
        }
        BmsDxOrder bmsDxOrder = bmsDxOrderOptional.get();
        if (!bmsDxOrder.getOrderNo().equals(orderNo)) {
            return ResultMapHelper.result(ResultCode.CODE_ORDER_ID_NOMATCH_NO, ResultMsg.CODE_ORDER_ID_NOMATCH_NO);
        }
        BmsUser bmsUser = TokenManager.getUser(bmsDxOrder.getBmsUserId());
        if(bmsUser == null || StringUtils.isBlank(bmsUser.getAliUserId())){
            return ResultMapHelper.result(ResultCode.CODE_PAY_ID_GET_FIAR, "业务参数缺失，支付凭证获取失败");
        }
        Map<String, Object> checkMap = bmsDxOrderService.checkOrderCanPay(bmsDxOrder);
        if (!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())) {
            return checkMap;
        }
        String totalAmt = bmsDxOrder.getActualConsum().toString();
        log.info("下单动用的支付宝配置：" + JSON.toJSONString(aliMiniAppConfig));
        try {
            // 这个东西必备
            AlipayClient alipayClient = new DefaultAlipayClient(
                    aliMiniAppConfig.getServerUrl(),
                    aliMiniAppConfig.getAppid(),
                    aliMiniAppConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    aliMiniAppConfig.getPublicKey(),
                    "RSA2");
            // 发起App支付请求
            AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
            AlipayTradePayModel model = new AlipayTradePayModel();
            // 订单描述
            model.setBody(AlipayServiceImpl.PAY_DEFAULT_DESC);
            // 订单标题
            model.setSubject(aliPayService.getOrderSubject(bmsDxOrder));
            // 商户订单号 就是商户后台生成的订单号
            model.setOutTradeNo(orderNo);
            // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天 (屁股后面的字母一定要带，不然报错)
            model.setTimeoutExpress("30m");
            // 订单总金额 ，默认单位为元，精确到小数点后两位，取值范围[0.01,100000000]
            model.setTotalAmount(totalAmt);
            model.setBuyerId(bmsUser.getAliUserId());
            request.setBizModel(model);
            request.setNotifyUrl(aliMiniAppConfig.getCallBackUrl());
            // 通过api的方法请求阿里接口获得反馈
            AlipayTradeCreateResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                //TODO 保存订单
                String result = response.getBody();
                log.info("请求的结果：" + result);
                resultMap.put("tradeNo",response.getTradeNo());
                bmsDxOrder.setPayWay(Constants.ALI_PAY);
                bmsDxOrderService.getBaseDao().save(bmsDxOrder);
                return ResultMapHelper.success(resultMap, ResultMsg.MSG_GET_SUCCESS);
            }
        } catch (Exception e) {
            log.error("下单失败 ----- ",e);
        }
        return ResultMapHelper.result(ResultCode.CODE_PAY_ID_GET_FIAR, "业务参数缺失，支付凭证获取失败");
    }

    /**
     * 本地生活分享二维码
     * @return
     */
    @PostMapping("/getShareCode")
    @ResponseBody
    public Map<String,Object> getShareCode(@RequestBody ParamsMap paramsMap) {
        try{
            Integer lifeId = Integer.parseInt(String.valueOf(paramsMap.get("lifeId")));
            //初始化
            AlipayClient alipayClient = new DefaultAlipayClient(
                    aliMiniAppConfig.getServerUrl(),
                    aliMiniAppConfig.getAppid(),
                    aliMiniAppConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    aliMiniAppConfig.getPublicKey(),
                    "RSA2");
            AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();
            request.setBizContent("{" +
                    "\"url_param\":\"pages/localLife/shopping\"," +
                    "\"query_param\":\"id="+lifeId+"\"," +
                    "\"describe\":\"二维码描述\"" +
                    "}");
            AlipayOpenAppQrcodeCreateResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return ResultMapHelper.success(response.getQrCodeUrl(), "调取成功");
            } else {
                return ResultMapHelper.failure("调取失败");
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return ResultMapHelper.failure("调取失败");
        }
    }
}
